package com.yu.helper;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.yu.entity.Auth.JwtUserEntity;
import com.yu.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Date;
import java.util.Objects;

/**
 * token 帮助类
 *
 * @author maxinyu
 * @date 2025-6-4
 */
@Slf4j
@Component
public class TokenHelper {
    // ✅ 自动生成符合 HS512 要求的密钥（512位）
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512);

    private static final String SECRET_STRING = Base64.getEncoder().encodeToString(SECRET_KEY.getEncoded());

    @Value("${mall.mgt.tokenSecret:#{T(java.util.Base64).getEncoder().encodeToString(T(io.jsonwebtoken.security.Keys).secretKeyFor(T(io.jsonwebtoken.SignatureAlgorithm).HS512).getEncoded())}}")
    private String tokenSecret; // 可选：从配置中注入，否则用默认值

    private static final long EXPIRATION = 86400000; // 24小时

    private static final String TOKEN_PREFIX = "token:";
    private static final String USER_PREFIX = "user:";

//    @Value("${mall.mgt.tokenSecret:123456test}")
//    private String tokenSecret;
    @Value("${mall.mgt.tokenExpireTimeInRecord:3600}")
    private int tokenExpireTimeInRecord;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 生成token
     *
     * @param userDetails 用户信息
     * @return token
     */
    public String generateToken(UserDetails userDetails) {
        String username = userDetails.getUsername();
        String token = Jwts.builder()
                .setSubject(username)//主题
                .setExpiration(new java.util.Date(System.currentTimeMillis() + EXPIRATION))//过期时间
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)//签名算法
                .compact();
        redisUtils.set(getTokenKey(username), token, tokenExpireTimeInRecord);//保存token
        String userStr = JSON.toJSONString(userDetails);//保存用户详情
        redisUtils.set(getUserKey(username), userStr, tokenExpireTimeInRecord);//保存用户详情到redis数据库
        return token;
    }


    private String getTokenKey(String username) {
        return getKey(TOKEN_PREFIX, username);
    }

    private String getUserKey(String username) {
        return getKey(USER_PREFIX, username);
    }

    /**
     * 从token中解析出username
     *
     * @param token token
     * @return username
     */
    public String getUsernameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        if (Objects.isNull(claims)) {
            return null;
        }
        return claims.getSubject();
    }

    /**
     * 根据用户名称查询用户详情信息
     *
     * @param username 用户名称
     * @return 用户详情
     */
    public UserDetails getUserDetailsFromUsername(String username) {
        String userKey = getUserKey(username);
        String userDetailJson = redisUtils.get(userKey);
        if (!StringUtils.hasLength(userDetailJson)) {
            return null;
        }
        return JSON.parseObject(userDetailJson, JwtUserEntity.class);
         //return JSON.parseObject(userDetailJson, JwtUserEntity.class);
    }

    /**
     * 获得 Claims
     *
     * @param token Token
     * @return Claims
     */

    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(tokenSecret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.warn("获得 Claims失败：", e);
            claims = null;
        }
        return claims;
    }


    /**
     * 获取token
     *
     * @param username 用户名称
     * @return token
     */
    public String getToken(String username) {
        return redisUtils.get(getKey(TOKEN_PREFIX, username));
    }

    /**
     * 删除token
     *
     * @param token 用户名称
     */
    public void delToken(String token) {
        String username = getUsernameFromToken(token);
        redisUtils.del(getKey(TOKEN_PREFIX, username));
        redisUtils.del(getKey(USER_PREFIX, username));
    }

    /**
     * 获取用户详情
     *
     * @param username 用户名称
     * @return 用户详情
     */
    public UserDetails getUserDetails(String username) {
        String userJson = redisUtils.get(getKey(USER_PREFIX, username));
        return JSONUtil.toBean(userJson, UserDetails.class);
    }

    private String getKey(String prefix, String userName) {
        return String.format("%s%s", prefix, userName);
    }

    /**
     * 计算过期时间
     *
     * @return Date
     */
    private Date generateExpired() {
        return new Date(System.currentTimeMillis() + tokenExpireTimeInRecord * 1000);
    }
}